package com.hontech.bv.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.TextView
import com.hontech.bv.R
import com.hontech.bv.task.onClick
import com.hontech.bv.ui.window.showErr
import com.hontech.bv.utils.toInt

class FormView(ctx: Context, attrs: AttributeSet) : FrameLayout(ctx, attrs) {

    val tvName: TextView
    val etInput: EditText
    val btnSet: Button

    var clickFunc: suspend (Int) -> Unit = {}

    init {
        val view = LayoutInflater.from(ctx).inflate(R.layout.view_form, this)

        tvName = view.findViewById(R.id.id_form_tv_name)
        etInput = view.findViewById(R.id.id_form_et_input)
        btnSet = view.findViewById(R.id.id_form_btn_set)


        val attr = ctx.obtainStyledAttributes(attrs, R.styleable.FormView)

        val name = attr.getText(R.styleable.FormView_tv_name)
        tvName.text = name

        val def = attr.getInteger(R.styleable.FormView_et_def, 0)
        etInput.setText("$def")

        val btn = attr.getString(R.styleable.FormView_btn_name)
        btnSet.text = btn

        attr.recycle()

        btnSet.onClick {
            val input = try {
                etInput.toInt()
            } catch (e: Exception) {
                e.printStackTrace()
                showErr("请输入参数", tvName.text.toString())
                return@onClick
            }
            clickFunc(input)
        }
    }



}